package com.twittex.model
{
	import com.adobe.serialization.json.JSON;
	import com.arc90.rpc.events.FaultEvent;
	import com.arc90.rpc.events.ResultEvent;
	import com.arc90.rpc.rest.RESTService;
	import com.arc90.rpc.rest.RESTServiceMethod;
	import com.twittex.TwittexFacade;
	import com.twittex.model.vo.UserVO;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class UserProxy extends Proxy
	{
		public static const NAME:String = "UserProxy";

		private static const TWITTER_USER_SHOW:String = "http://twitter.com/users/show/";

		public function UserProxy(proxyName:String=null, data:Object=null)
		{
			super(NAME, data);
		}
		
		public function get userVO():UserVO {
			return data as UserVO;
		}
		
		public function show(force:Boolean=false):void {
			if(!userVO || force) {
				var service:RESTService = new RESTService();
	
				service.url = TWITTER_USER_SHOW + userVO.name + ".json";
				service.method = RESTServiceMethod.GET;
				service.resultFormat = RESTService.RESULT_FORMAT_TEXT;
					
				var successHandler:Function = function (event:ResultEvent):void {
					var rawData:String = String(event.result);
					var user:UserVO = new UserVO(JSON.decode(rawData));

					setData(user);	
					sendNotification(TwittexFacade.USER_FOUND, user);
				}
				
				var failHandler:Function = function (event:FaultEvent):void {
					// TODO: Send notification user not found
				}
	
				service.addEventListener(ResultEvent.RESULT, successHandler);
				service.addEventListener(FaultEvent.FAULT, failHandler);
				service.send();
			} else {
				sendNotification(TwittexFacade.USER_FOUND, userVO);	
			}
		}
		
	}
}